package io.renren.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import org.springframework.stereotype.Controller;

import io.renren.dao.PersonnelDao;
import io.renren.entity.Crossborderalarm;
import io.renren.entity.Disappearalarm;
import io.renren.entity.GroupPersonnel;
import io.renren.entity.Personnel;
import io.renren.service.CrossborderalarmService;
import io.renren.service.DisappearalarmService;
import io.renren.service.GroupPersonnelService;
import io.renren.service.PersonnelService;
import io.renren.utils.PageUtils;
import io.renren.utils.R;
import jxl.*;



/**
 * 
 * 
 * @author zk
 * @email zk13899@163.com
 * @date 2017-06-14 11:49:03
 */
@Controller
@RequestMapping("personnel")
public class PersonnelController {
	
	@Autowired
	private PersonnelService personnelService;
	@Autowired
	private CrossborderalarmService crossborderalarmService;
	@Autowired
	private GroupPersonnelService groupPersonnelService;
	@Autowired
	private DisappearalarmService disappearalarmService;
	@RequestMapping("/personnel.html")
	public String list(){
		return "personnel/personnel.html";
	}
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("personnel:list")
	public R list(Integer page, Integer limit,Integer idGroupPersonnel,String str){
		Map<String, Object> map = new HashMap<>();
		String str1=str;
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		map.put("str", str);
		map.put("idGroupPersonnel", idGroupPersonnel);
		//查询列表数据
		List<Personnel> personnelList = personnelService.queryList(map);
		System.out.println(personnelList+"------------------------------------");
		int total = personnelService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(personnelList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	/* 人员分组列表 */
	@ResponseBody
	@RequestMapping("/grouppersonnel/list")

	public R arealist() {
		Map<String, Object> map = new HashMap<>();
		List<GroupPersonnel> listGroupPersonnel = groupPersonnelService.queryList(map);

		return R.ok().put("listGroupPersonnel", listGroupPersonnel);
	}
	/* 越界策略列表 */
	@ResponseBody
	@RequestMapping("/crossborderalarm/list")
	
	public R celuelist() {
		Map<String, Object> map = new HashMap<>();
		List<Crossborderalarm> listCrossborderalarm = crossborderalarmService.queryList(map);
		
		return R.ok().put("listCrossborderalarm", listCrossborderalarm);
	}
	/* 离岗侧略列表 */
	@ResponseBody
	@RequestMapping("/disappearalarm/list")
	
	public R leavelist() {
		Map<String, Object> map = new HashMap<>();
		List<Disappearalarm> listDisappearalarm = disappearalarmService.queryList(map);
		
		return R.ok().put("listDisappearalarm", listDisappearalarm);
	}
	/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("personnel:info")
	public R info(@PathVariable("id") Integer id){
		Personnel personnel = personnelService.queryObject(id);
		
		return R.ok().put("personnel", personnel);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("personnel:save")
	public R save(@RequestBody Personnel personnel){
		personnelService.save(personnel);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("personnel:update")
	public R update(@RequestBody Personnel personnel){
		personnelService.update(personnel);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("personnel:delete")
	public R delete(@RequestBody Integer[] ids){
		personnelService.deleteBatch(ids);
		
		return R.ok();
		
	}
	public  File getExcelDemoFile(String fileDir) throws Exception{
		String classDir = null;
		String fileBaseDir = null;
		File file = null;
		classDir = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
		fileBaseDir = classDir.substring(0, classDir.lastIndexOf("classes"));
		
		file = new File(fileBaseDir+fileDir);
		if(!file.exists()){
			throw new Exception("模板文件不存在！");
		}
		return file;
	}
	
	//导出数据到excel
    @RequestMapping("/export")
  	//@SuppressWarnings("deprecation")
  	public String export2(HttpServletResponse response) throws Exception{
    	Map<String, Object> map = new HashMap<>();
  		//如果是从数据库里面取数据 userList
  		List<Personnel> userList = personnelService.queryList(map);// 用户集合
  		
  		System.out.println("++++++++++++++++++++++"+userList);
  		
  		 // 设置表头：对Excel每列取名(必须根据你取的数据编写)
  		 
  		String[] tableHeader = { "姓名", "身份证", "联系方式", "标签", "组别", "越界策略", "离岗策略"
  		};
  		
  		 //下面的都可以拷贝不用编写
  		 
  		short cellNumber = (short) tableHeader.length;// 表的列数
  		HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel
  		HSSFCell cell = null; // Excel的列
  		HSSFRow row = null; // Excel的行
  		HSSFCellStyle style = workbook.createCellStyle(); // 设置表头的类型
  		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		HSSFCellStyle style1 = workbook.createCellStyle(); // 设置数据类型
  		style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		HSSFFont font = workbook.createFont(); // 设置字体
  		HSSFSheet sheet = workbook.createSheet("sheet1"); // 创建一个sheet
  		HSSFHeader header = sheet.getHeader();// 设置sheet的头
  		try {
  			//**
  			 // 根据是否取出数据，设置header信息
  			  
  			 //*
  			if (userList.size() < 1) {
  				header.setCenter("查无资料");
  			} else {
  				System.out.println("导出表格的尺寸="+userList);
  				header.setCenter("公司表");
  				row = sheet.createRow(0);
  				row.setHeight((short) 400);
  				for (int k = 0; k < cellNumber; k++) {
  					cell = row.createCell(k);// 创建第0行第k列
  					cell.setCellValue(tableHeader[k]);// 设置第0行第k列的值
  					sheet.setColumnWidth(k, 5000);// 设置列的宽度
  					font.setColor(HSSFFont.COLOR_NORMAL); // 设置单元格字体的颜色.
  					font.setFontHeight((short) 200); // 设置单元字体高度
  					style1.setFont(font);// 设置字体风格
  					cell.setCellStyle(style1);
  				}
  				
  				  // 给excel填充数据这里需要编写
  				 
  				for (int i = 0; i < userList.size(); i++) {
  					Personnel user = (Personnel) userList.get(i);// 获取company对象
  					row = sheet.createRow((short) (i + 1));// 创建第i+1行
  					row.setHeight((short) 400);// 设置行高

  					if (user.getName() != null) {
  						cell = row.createCell(0);// 创建第i+1行第0列
  						cell.setCellValue(user.getName());// 设置第i+1行第0列的值
  						cell.setCellStyle(style);// 设置风格
  					}
  					if (user.getNric() != null) {//自己设置 的联系人不能为空
  						cell = row.createCell(1); // 创建第i+1行第1列
  						cell.setCellValue(user.getNric());// 设置第i+1行第1列的值
  						cell.setCellStyle(style); // 设置风格
  					}
  					// 由于下面的和上面的基本相同，就不加注释了
  					if (user.getContact() != null) {
  						cell = row.createCell(2);
  						cell.setCellValue(user.getContact());
  						cell.setCellStyle(style);
  					}
  					if (user.getCodeTag()!= null) {  
  						cell = row.createCell(3);
  						cell.setCellValue(user.getCodeTag());
  						cell.setCellStyle(style);
  					}
  					if (user.getIdGroupPersonnel() !=null) {
  						cell = row.createCell(4);
  						cell.setCellValue(user.getIdGroupPersonnel());
  						cell.setCellStyle(style);
  					}
  					if (user.getIdCrossborderalarm() != null) {
  						cell = row.createCell(5);
  						cell.setCellValue(user.getIdCrossborderalarm());
  						cell.setCellStyle(style);
  					}
  					if (user.getIdDisappearalarm() != null) {
  						cell = row.createCell(6);
  						cell.setCellValue(user.getIdDisappearalarm());
  						cell.setCellStyle(style);
  					}
  					
  				}
  			}
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  		
  		 // 下面的可以不用编写，直接拷贝
  		 
  		
  			OutputStream out = null;// 创建一个输出流对象
  			try {
  				
  				out = response.getOutputStream();//
  				response.setHeader("Content-disposition", "attachment; filename="
  						+ "company.xls");// filename是下载的xls的名，建议最好用英文
  				response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
  				response.setHeader("Pragma", "No-cache");// 设置头
  				response.setHeader("Cache-Control", "no-cache");// 设置头
  				response.setDateHeader("Expires", 0);// 设置日期头
  				workbook.write(out);
  				out.flush();
  				workbook.write(out);
  			} catch (IOException e) {
  				e.printStackTrace();
  			} finally {
  				try {
  					if (out != null) {
  						out.close();
  					}
  				} catch (IOException e) {
  					e.printStackTrace();
  				}
  			}
  			return null;
  			
  	}

			
	//+++++++++++++++++++++++++++++++++++++++++
	 
		/**
		 * 描述：通过传统方式form表单提交方式导入excel文件
		 * @param request
		 * @throws Exception
		 */
		@RequestMapping(value="upload.do",method={RequestMethod.GET,RequestMethod.POST})
		public  String  uploadExcel(HttpServletRequest request) throws Exception {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
			System.out.println("通过传统方式form表单提交方式导入excel文件！");
			
			InputStream in =null;
			List<List<Object>> listob = null;
			MultipartFile file = multipartRequest.getFile("upfile");
			if(file.isEmpty()){
				throw new Exception("文件不存在！");
			}
	 		in = file.getInputStream();
	 		System.out.println(in+""+file+"+++++++++++++++++++");
			listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
			in.close();
			List<Personnel> list = new ArrayList<Personnel>();
			//该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
			for (int i = 0; i < listob.size(); i++) {
	   			List<Object>lo = listob.get(i);
				Personnel vo = new Personnel();
				vo.setName(String.valueOf(lo.get(0)));
				vo.setNric(String.valueOf(lo.get(1)));
				vo.setCodeTag(String.valueOf(lo.get(2)));
				vo.setContact(String.valueOf(lo.get(3)));
				vo.setIdGroupPersonnel(Integer.valueOf(lo.get(4)+""));
				vo.setIdCrossborderalarm(Integer.valueOf(lo.get(5)+""));
				vo.setIdDisappearalarm(Integer.valueOf(lo.get(6)+""));
				list.add(vo);
				System.out.println("打印信息-->姓名:"+vo.getName()+" ----- 身份证："+vo.getNric()+"  --- 联系方式："+vo.getContact()+" ---  标签："+vo.getCodeTag()+
				 "--- 组别"+vo.getIdGroupPersonnel()+"---越界策略"+vo.getIdCrossborderalarm()+"------离岗策略"+vo.getIdDisappearalarm());
			}
			System.out.println("+++++++++++++++++123"+list);
			    personnelService.addBatch(list);
			
			return "dingwei/personnel.html";
		}
}
